//
//  WHYOauthViewController.m
//  WHYWeibo-OC
//
//  Created by 王洪运 on 15/11/24.
//  Copyright © 2015年 王洪运. All rights reserved.
//

#import "WHYOauthViewController.h"
#import "WHYNetworkTools.h"
#import <SVProgressHUD/SVProgressHUD.h>

@interface WHYOauthViewController ()<UIWebViewDelegate>

@property (strong, nonatomic) UIWebView *webView;

@end

@implementation WHYOauthViewController
#pragma mark - 懒加载
-(UIWebView *)webView {
    if (_webView == nil) {
        _webView = [UIWebView new];
    }
    return _webView;
}

#pragma mark - 监听按钮事件
-(void)clickCloseBarButtonItem {
    [self dismissViewControllerAnimated:YES completion:nil];
}

-(void)clickAutoFillBarButtonItem {
    NSString *js = @"document.getElementById('userId').value = 'zhigaoxuanshang@sina.com';"
    "document.getElementById('passwd').value = '71938183why';";
    [self.webView stringByEvaluatingJavaScriptFromString:js];
}

#pragma mark - 视图声明周期方法
- (void)viewDidLoad {
    [super viewDidLoad];

    [self.webView loadRequest:[NSURLRequest requestWithURL:[WHYNetworkTools sharedTools].oauthURL]];
}

-(void)loadView {
    self.view = self.webView;
    self.title = @"登陆新浪微博";
    self.webView.delegate = self;
    
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"关闭" style:UIBarButtonItemStylePlain target:self action:@selector(clickCloseBarButtonItem)];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"自动填充" style:UIBarButtonItemStylePlain target:self action:@selector(clickAutoFillBarButtonItem)];
}

#pragma mark - webView代理方法
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType {
    
    if (![request.URL.host isEqualToString:@"www.baidu.com"]) {
        return YES;
    }
    
    if ([request.URL.query hasPrefix:@"code="]) {
        NSString *code = [request.URL.query substringFromIndex:5];
        NSLog(@"%@",code);
        [[WHYNetworkTools sharedTools] loadAccessTokenWithCode:code finished:^(id result, NSError *error) {
            if (error != nil) {
                NSLog(@"%@",error);
                return ;
            }
            NSLog(@"%@",result);
        }];
    }
    
    return NO;
}

- (void)webViewDidStartLoad:(UIWebView *)webView {
    [SVProgressHUD show];
}

- (void)webViewDidFinishLoad:(UIWebView *)webView {
    [SVProgressHUD dismiss];
}

- (void)webView:(UIWebView *)webView didFailLoadWithError:(nullable NSError *)error {
    if (error.code == 102) {
        [SVProgressHUD dismiss];
    }else {
        [SVProgressHUD showErrorWithStatus:@"您的网络不给力"];
    }
}
@end
